package com.dc.member.controller;

import com.alibaba.fastjson.JSONObject;
import com.dc.base.BaseResponse;
import com.dc.member.controller.req.vo.RegisterVo;
import com.dc.member.feign.IMemberRegisterServiceFeignPortal;
import com.dc.member.input.dto.UserInputDTO;
import com.dc.web.base.BaseWebController;
import com.dc.web.bean.DcBeanUtils;
import com.dc.web.utils.RandomValidateCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

/**
 * @author: KEYD
 * @Date: 2019/12/29 11:19
 * @Desc: 注册控制层
 */
@Controller
public class RegisterController extends BaseWebController {
    private static final String MEMBER_REGISTER_FTL = "member/register";  //注册页面
    private static final String MEMBER_LOGIN_FTL = "member/login";  // 跳转到登录页面

    @Autowired
    private IMemberRegisterServiceFeignPortal iMemberRegisterServiceFeignPortal;

    /**
     * 跳转到注册页面
     *
     * @return
     */
    @GetMapping("/register")
    public String getRegister() {
        return MEMBER_REGISTER_FTL;
    }

    /**
     * 跳转到注册页面
     *
     * @return
     * @ModelAttribute("registerVo") 参数回显
     * @Validated 参数验证
     */
    @PostMapping("/register")
    public String postRegister(@ModelAttribute("registerVo") @Validated RegisterVo registerVo, BindingResult bindingResult, Model model, HttpSession httpSession) { //param 不能变
        //1、接受表单参数(验证码) 创建对象接受参数
        if (bindingResult.hasErrors()) {
            //如果参数有错的
            String errorMsg = bindingResult.getFieldError().getDefaultMessage();
            setErrorMsg(model, errorMsg);
            return MEMBER_REGISTER_FTL;  //验证失败，重新
        }
        //2、判断图形验证码是否正确
        String graphicCode = registerVo.getGraphicCode();
        Boolean checkVerify = RandomValidateCodeUtil.checkVerify(graphicCode, httpSession);// 图形验证码存放在session中
        if (!checkVerify) {
            setErrorMsg(model, "图形验证码不正确");
            return MEMBER_REGISTER_FTL;
        }

        //3、调用会员服务接口实现注册
        //vo dto 转换
        UserInputDTO userInputDTO = DcBeanUtils.voToDto(registerVo, UserInputDTO.class);
        BaseResponse<JSONObject> register = iMemberRegisterServiceFeignPortal.register(userInputDTO, registerVo.getRegistCode());
        if (!isSuccess(register)) {   //父类里面先定义好
            setErrorMsg(model, register.getMsg());
            return MEMBER_REGISTER_FTL;
        }
        //4、注册成功，跳转到登录页面
        return MEMBER_LOGIN_FTL;
    }

}
